package com.teatang.tadmin.index.controller;

import com.teatang.tadmin.config.TAdminConfig;
import com.teatang.tadmin.core.controller.BasePageController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexPageController extends BasePageController {

    @RequiresPermissions("sys:index-page:index")
    @RequestMapping("/")
    public String index() {
        return "index/index";
    }

    @RequiresPermissions("sys:index-page:welcome-1")
    @RequestMapping("/index-page/welcome-1.html")
    public String welcome1() {
        return "index/welcome-1";
    }

    @RequestMapping("/index-page/login")
    public String login(Model model) {
        model.addAttribute("title", TAdminConfig.getName());
        return "index/login";
    }

    @RequestMapping("/index-page/toLogin")
    public String toLogin(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model
    ) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            model.addAttribute("errMsg", "用户名错误");
            return "index/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("errMsg", "密码错误");
            return "index/login";
        }

        return "redirect:/";
    }

    @RequestMapping("/index-page/no-auth")
    public String noAuth() {
        return "error/no-auth";
    }

    @RequestMapping("/index-page/404")
    public String go404() {
        return "error/404";
    }
}
